package com.xxx.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 读取配置文件
 * 
 * 
 * 
 */
public class PropertyUtil extends PropertyPlaceholderConfigurer {

	private static Map<String, String> ctxproperty = new HashMap<>();

	/**
	 * 读取配置文件，将配置内容存放到map中
	 */
	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
			throws BeansException {
		super.processProperties(beanFactoryToProcess, props);
		for (Object prop : props.keySet()) {
			String key = prop.toString();
			String value = props.getProperty(key);
			ctxproperty.put(key, value);
		}
	}

	/**
	 * 根据key，获取value
	 * @param key
	 * @return
	 */
	public static String getCtxProperty(String key) {
		return ctxproperty.get(key);
	}
	
	/**
	 * 读取指定路径的配置文件
	 * @param path
	 * @return
	 */
	public static Properties getProperties(String path) {
		FileInputStream fis = null;
		Reader read = null;
		Properties prop = null;
		
		try {
			fis = new FileInputStream(path);
			read = new InputStreamReader(fis,"UTF-8");
			prop = new Properties();
			prop.load(read);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if( read != null) {
					read.close();
				}
				if( fis != null) {
					fis.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		
		return prop;
	}
	
	/**
	 * 根据key获取value
	 * @param prop
	 * @param key
	 * @return
	 */
	public static String getValue(Properties prop, String key) {
		if(prop != null) {
			if(prop.containsKey(key)) {
				return (String)prop.get(key);
			}
		}
		return "";
	}
}
